const os = require('os')
const path = require('path')
const { readFileSync } = require('fs')
const loaderUtils = require('loader-utils')

const networkInterfaces = os.networkInterfaces()
let internalIp = '127.0.0.1'
if (networkInterfaces && networkInterfaces.en0) {
  for (let i in networkInterfaces.en0) {
    const interface = networkInterfaces.en0[i]
    if (interface.family === 'IPv6') continue
    internalIp = interface.address
  }
}

// 工程根目录rootPath
const rootPath = path.resolve(__dirname, '../../')

module.exports = function() {
  const loaderOptions = loaderUtils.getOptions(this)
  // 如果 localImageUseHttpRequestEnvs 数组中包含 process.env.NODE_ENV，则图片采用http路径加载 
  const imgUseHttpMode = loaderOptions.localImageUseHttpRequestEnvs.indexOf(process.env.NODE_ENV) > -1 ;
  const imagePath = this.resource;

  //console.log('imagePath = ' + imagePath);

  let splitArg = path.join('/', 'src');
  let src = imagePath.split(splitArg)[1];

  if (!src) throw new Error('静态资源必须放置在 src 文件夹里面');

  if (!imgUseHttpMode) {
    // 复制到 dist
    this.emitFile(src, readFileSync(imagePath));
  } else {
    src = imagePath.split(rootPath)[1];
  }

  let filepath1 = src.replace(/\\/g, '/');
  let filepath2 = filepath1;
  if (filepath1.substring(0, 1) == '/') {
    filepath2 = filepath1.substring(1);
  }

  let retStr = '';
  if (imgUseHttpMode) {
    //`http://${loaderOptions.imageHost || internalIp}:${loaderOptions.port || '12345'}${filepath1}`;
    // 上面是生成 http 路径的方案，但是目前flutter已经兼容了相对路径的资源加载，所以没有必要，就用相对路径就好。
    retStr = filepath2;
  } else {
    retStr = filepath2;
  }

  console.log('load resource: ' + retStr);

  return `export default '${retStr}'`;
}
